package com.twu.biblioteca.command;

import com.twu.biblioteca.Library.User;
import com.twu.biblioteca.service.BookService;
import com.twu.biblioteca.tools.UserFactory;
import com.twu.biblioteca.view.MessageView;

import java.io.BufferedReader;
import java.io.IOException;
import java.security.InvalidParameterException;

public class CheckoutBook extends Command {
    private User user;
    private BookService bookService;
    private BufferedReader reader;

    public CheckoutBook(BookService bookService, User user, MessageView messageView, BufferedReader reader) {
        super(messageView);
        this.user = user;
        this.bookService = bookService;
        this.reader = reader;
    }

    @Override
    public void execute() {
        getMessageView().showMessage(MessageView.BOOK_NAME);
        try {
            String bookName = reader.readLine();
            UserFactory.checkLogin(user);
            bookService.checkOutBook(bookName, user.getUserName());
            getMessageView().showMessage(MessageView.CHECK_OUT_SUCCESS);
        } catch (InvalidParameterException e) {
            getMessageView().showMessage(MessageView.INVALID_BOOK_NAME);
        } catch (NullPointerException e) {
            getMessageView().showMessage(MessageView.HAVE_NOT_LOGIN);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
